//
//  DR_HomeFileCell.swift
//  DocReaderRP
//
//  Created by  mac on 2025/11/14.
//

import UIKit
import SnapKit

class DR_HomeFileCell: UICollectionViewCell {
    
    static let identifier = "DR_HomeFileCell"
    
    var onFavoriteTapped: (() -> Void)?
    var onMoreTapped: (() -> Void)?
    
    private let thumbnailImageView: UIImageView = {
        let imageView = UIImageView()
        imageView.contentMode = .scaleAspectFill
        imageView.backgroundColor = "#F6F7FF".toColor
        imageView.layer.cornerRadius = 20
        imageView.layer.masksToBounds = true
        imageView.isUserInteractionEnabled = true
        return imageView
    }()
    
    private let fileNameLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFont(ofSize: 14, weight: .medium)
        label.textColor = .black
        label.lineBreakMode = .byTruncatingMiddle
        label.textAlignment = .center
        return label
    }()
    
    private let metadataLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFont(ofSize: 12)
        label.textColor = "#ADADAD".toColor
        label.textAlignment = .center
        return label
    }()
    
    private let favoriteButton: UIButton = {
        let button = UIButton(type: .custom)
        button.setImage(UIImage(named: "home_collect"), for: .normal)
        button.setImage(UIImage(named: "home_collected"), for: .selected)
        return button
    }()
    
    private let moreButton: UIButton = {
        let button = UIButton(type: .custom)
        button.setImage(UIImage(named: "home_more"), for: .normal)
        return button
    }()
    
    private let typeImage: UIImageView = {
        let v = UIImageView()
        v.image = "home_pdf".toImage
        return v
    }()
    
    private let fileImage: UIImageView = {
        let v = UIImageView()
        v.image = "home_file".toImage
        v.contentMode = .scaleAspectFill
        return v
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
        setupConstraints()
        setupActions()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {

        contentView.addSubview(thumbnailImageView)
        contentView.addSubview(fileNameLabel)
        contentView.addSubview(metadataLabel)
        thumbnailImageView.addSubview(favoriteButton)
        thumbnailImageView.addSubview(typeImage)
        thumbnailImageView.addSubview(fileImage)
        contentView.addSubview(moreButton)
    }
    
    private func setupConstraints() {

        thumbnailImageView.snp.makeConstraints { make in
            make.top.leading.trailing.equalToSuperview()
            make.height.equalTo(148)
        }
        
        fileNameLabel.snp.makeConstraints { make in
            make.top.equalTo(thumbnailImageView.snp.bottom).offset(6)
            make.leading.trailing.equalToSuperview().inset(5)
            make.height.equalTo(16)
        }
        
        metadataLabel.snp.makeConstraints { make in
            make.top.equalTo(fileNameLabel.snp.bottom).offset(6)
            make.leading.trailing.equalToSuperview().inset(5)
            make.height.equalTo(14)
        }
        
        favoriteButton.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.bottom.equalToSuperview().offset(-6)
            make.width.height.equalTo(24)
        }
        
        typeImage.snp.makeConstraints { make in
            make.top.leading.equalToSuperview().offset(10)
            make.width.equalTo(40)
            make.height.equalTo(20)
        }
        
        fileImage.snp.makeConstraints { make in
            make.centerX.centerY.equalToSuperview()
            make.width.height.equalTo(44)
        }
        
        moreButton.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.bottom.equalToSuperview()
            make.width.equalTo(25)
            make.height.equalTo(16)
        }
    }
    
    private func setupActions() {
        favoriteButton.addTarget(self, action: #selector(favoriteButtonTapped), for: .touchUpInside)
        moreButton.addTarget(self, action: #selector(moreButtonTapped), for: .touchUpInside)
    }
    
    @objc private func favoriteButtonTapped() {
        favoriteButton.isSelected = !favoriteButton.isSelected
        onFavoriteTapped?()
    }
    
    @objc private func moreButtonTapped() {
        onMoreTapped?()
    }
    
    func configure(with fileModel: DR_FileModel, isFavorite: Bool = false, hideTypeImage: Bool = false) {
        fileNameLabel.text = fileModel.displayName
        
        // 格式化日期和大小
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd"
        let dateString = dateFormatter.string(from: fileModel.createDate)
        metadataLabel.text = "\(dateString) \(fileModel.fileSizeString)"
        
        // 设置收藏状态
        favoriteButton.isSelected = isFavorite
        
        // 根据文件类型设置图标（如果不需要隐藏）
        if !hideTypeImage {
            typeImage.image = UIImage(named: fileModel.fileType.iconName)
            typeImage.isHidden = false
        } else {
            typeImage.isHidden = true
        }
        
        if fileModel.fileType == .pdf {
            // 加载文件预览图（异步）
            fileImage.isHidden = true
            loadThumbnail(for: fileModel.fileURL, fileType: fileModel.fileType)
        }else{
            fileImage.isHidden = false
            thumbnailImageView.image = "".toImage
        }
        
    }
    
    // 兼容旧接口
    func configure(with pdfModel: DR_PDFFileModel, isFavorite: Bool = false, hideTypeImage: Bool = false) {
        let fileModel = DR_FileModel(from: pdfModel)
        configure(with: fileModel, isFavorite: isFavorite, hideTypeImage: hideTypeImage)
    }
    
    private func loadThumbnail(for fileURL: URL, fileType: DR_FileType) {
        DispatchQueue.global(qos: .userInitiated).async { [weak self] in
            let thumbnail = DR_FileManager.shared.getFileThumbnail(fileURL: fileURL, fileType: fileType, size: CGSize(width: 200, height: 240))
            
            DispatchQueue.main.async {
                self?.thumbnailImageView.image = thumbnail ?? UIImage(named: fileType.iconName)
            }
        }
    }
}

